<?php
namespace Mobile\Controller;
use Think\Controller;
use User\Api\UserApi;
use Api\Controller\ImageController;

class UserController extends Controller{
    
    private $userapi = '';
    private $www_url = '';
    private $chat_appkey = '';
    private $chat_appsecret = '';
    
    
    public function _initialize(){
        $this->userapi = new UserApi();
        $this->www_url = C('WWW_ROOT');
        $this->chat_appkey = C('appKey');
        $this->chat_appsecret = C('appSecret');
    }


    /**
     * 用户登录(当前只支持本地用户登录)
     * @param string $username 用户名
     * @param string $password 密码
     * @return json code:状态码；msg：状态信息；data：{id：用户id；token：聊天token；avatar_url：头像；nickname：昵称}
     */
    public function login($username = '', $password = ''){
        
        $id = $this->userapi->login($username, $password, 0, 0); //本地用户登录
        if($id > 0){
            $user = M('User')->field('nickname, avatar_url, usertype, status')->where(array('id' => $id))->find();
            
            //获取用户的token值，每次登陆获取一次（更换一次）
            vendor('Api.ServerAPI');
            $parm = array('userId'=>$id, 'name' => $user['nickname'], 'portraitUri' => $this->www_url . $user['avatar_url']);

            $p = new \ServerAPI($this->chat_appkey, $this->chat_appsecret);
            $r = $p->getToken($parm['userId'], $parm['name'], $parm['portraitUri']);
            $r = json_decode($r);
            
            if($r->code == 200){
                $tmp = array(
                    'id'            => $id,
                    'token'         => $r->token,
                    'avatar_url'    => $this->www_url . $user['avatar_url'],
                    'nickname'      => $user['nickname'],
                    'usertype'      => $user['usertype'],
                    'status'        => $user['status'],
                );
                $data = array("code"=>intval($id), "msg"=>"登录成功！", "data"=>$tmp);
            } else {
                $data = array("code"=>0, "msg"=>"token获取失败！");
            }            
        }else{            
            switch ($id){
                case -1: 
                    $error_msg = '用户名不存在！';
                    break;
                case -2:
                    $error_msg = '用户名密码不匹配！';
                    break;
                case -3:
                    $error_msg = '第三方连接错误！';
                    break;
                case -4:
                    $error_msg = '该用户被禁用！';
                    break;                
                default :
                    $error_msg = '登录不成功，请重新登录！';
            }
            $data = array("code"=>intval($id), "msg" => $error_msg);
        }
          $this->ajaxReturn($data);
    }
    
    /**
     * 用户注册 
     * @param string $username 用户名
     * @param string $password 密码
     * @param string $mobile 手机号
     * @return json Description
     */
    public function register($username = '', $password = '', $mobile = ''){

        //在用户表中添加数据
        $code = $this->userapi->register($username, $password, $mobile);
        if($code > 0){
            //在云模特表中添加记录
            $model = M("User_model");
            $user_model = array("uid" => $code, "nickname" => $username);
            $model->data($user_model)->add();

            $user = M('User')->field('avatar_url, status')->where(array('id' => $code))->find();
            //获取用户的token值
            vendor('Api.ServerAPI');
            $parm = array('userId'=>$code, 'name' => $username, 'portraitUri' => $this->www_url . $user['avatar_url']);

            $p = new \ServerAPI($this->chat_appkey, $this->chat_appsecret);
            $r = $p->getToken($parm['userId'], $parm['name'], $parm['portraitUri']);
            $r = json_decode($r);

            $tmp = array(
                'id'            => $code,
                'token'         => $r->token,
                'avatar_url'    => $this->www_url . $user['avatar_url'],
                'nickname'      => $username,
                'status'	=> $user['status'],
            );
            $data = array("code"=>$code, "msg"=>"登录成功！", "data"=>$tmp);
        }else{
            switch ($code){
            case -1: $msg = "用户名长度必须在2-16个字符以内！";
                break;
            case -2: $msg = "用户名只能由数字、字母和 _ 组成！";
                break;
            case -3: $msg = "用户名已存在！";
                break;
            case -4: $msg = "密码长度最少6个字符！";
                break;
            case -5: $msg = '电话号码长度不符！';
                break;
            case -6: $msg = '电话号码不正确！';
                break;
            case -7: $msg = '电话号码已存在！';
                break;
            default :
                $code = -8;
                $msg = "注册失败！";
            }
            $data = array("code" => $code, "msg" => $msg);
        }
        $this->ajaxReturn($data);
    }
    
    /**
     * 注册到老A
     * @param type $username
     * @param type $password
     * @param type $mobile
     */
    public function registerLaoA($username='', $password='', $mobile=''){
        
        $api = new UserApi();
        $user = $api->thirdRegister($username, $password, $mobile);       
        if($user['code'] > 0){
            $avatar = C('DEFAULT_AVATAR') . 'avatar(' . rand(1, 8) . ').jpg';
            $bg = C('DEFAULT_BACKGROUND') . 'bg(' . rand(1, 21) . ').jpg';
            $u_data = array(
                'third_id' => $user['code'],
                'last_login_time' => NOW_TIME,
                'reg_time' => NOW_TIME,
                'nickname' => $username,
                'username' => 'laoA_'.$username,
                'usertype' => 1,
                'avatar_url' => $avatar,
                'cover_img' => $bg,
            );
            $uid = M('User')->add($u_data);
            M("User_seller")->add(array('uid' => $uid, 'nickname' => $username));

            //获取用户的token值，每次登陆获取一次（更换一次）
            vendor('Api.ServerAPI');
            $parm = array('userId'=>$uid, 'name' => $username, 'portraitUri' => $this->www_url . $avatar);

            $p = new \ServerAPI($this->chat_appkey, $this->chat_appsecret);
            $r = $p->getToken($parm['userId'], $parm['name'], $parm['portraitUri']);
            $r = json_decode($r);

            $tmp = array(
                'id'            => $uid,
                'token'         => $r->token,
                'avatar_url'    => $this->www_url . $avatar,
                'nickname'      => $username,
            );
            //卖家基本权限设定,暂时写死设定权限：2
            M('Auth_group_access')->add(array('uid' => $uid, 'group_id' => 2)); 
            
            $data = array("code" => 1, "msg" => "注册成功！", "data" => $tmp);
        }else{
            $data = array('code' => $user['code'], 'msg' => $user['msg']);
        }
        $this->ajaxReturn($data);
    }
    
    /**
     * 像手机发送短信验证码
     */
    public function verifyMessage($mobile=''){
        $user = M('User')->where(array('mobile' => $mobile))->find();
        if(empty($user)){
            $this->ajaxReturn(array(
                'code'  => 3,
                'msg'   => '手机号不存在',
            ));
        }
        $num = $this->randNum();    //随机验证码
        $verify_time = C("VERIFY_TIME");    //验证码有效时间
        $verify = new \Api\Controller\MessageVerifyController;
        
        if(empty($user['verify'])){         //第一次发送验证码 
            $msg = $verify->sendTemplateSMS($mobile, array($num, $verify_time), 10406);
            //在数据库中保存验证码和有效时间
            M('User')->where(array('mobile' => $mobile))->save(array('verify' => $num, 'verify_time' => NOW_TIME));
//            if($msg['code'] == 1){                
//                session(array('verify' => $num, 'expire' => $verify_time));
//                session("time", time());
//            }
            $this->ajaxReturn($msg);         
        }else if(time() - $user['verify_time'] > 60){    //重发验证码（60之后）
            $msg = $verify->sendTemplateSMS($mobile, array($num, $verify_time), 10406);
            M('User')->where(array('mobile' => $mobile))->save(array('verify' => $num, 'verify_time' => NOW_TIME));
//            if($msg['code'] == 1){
//                session(array('verify' => $num, 'expire' => $verify_time));
//                session("time", time());
//            }
            $this->ajaxReturn($msg);
        }else{
            $this->ajaxReturn(array("code"=>2, "msg"=>"操作太频繁，请稍后重试"));
        }        
    }
    
    /*
     * 生成6个随机数字做验证码
     */
    public function randNum(){
        $num = "";
        for($i=0; $i<6; $i++){
            $num .= rand(0, 9);
        }
        return $num;
    }
    
    /**
     * 通过手机号重设密码
     * @param string $verify 用户输入验证码
     * @param string $newPwd 新密码
     * @param string $mobile 手机号
     */
    public function getPwdByPhone($verify='', $newPwd='', $mobile=''){
        $mobile = trim($mobile);
        $user = M('User')->where(array('mobile' => $mobile))->find();
        if(empty($user)){
            $this->ajaxReturn(array(
                'code'  => 0,
                'msg'   => '手机号码不存在',
            ));
        }
        if((time() - $user['verify_time'])/60 > 2){
            $this->ajaxReturn(array(
                'code'  => 0,
                'msg'   => '验证码超时',
            ));
        }
        if(trim($verify) == '' || trim($verify) != $user['verify']){
            $this->ajaxReturn(array(
                'code'  => 0,
                'msg'   => '验证码错误',
            ));
        }
        if($newPwd == ''){
            $this->ajaxReturn(array(
                'code'  => 2,
                'msg'   => '密码不能为空'
            ));
        }
        if(M('User')->where(array('mobile' => $mobile))->save(array('password' => md5($newPwd)))){
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '密码修改成功'
            ));
        }
        $this->ajaxReturn(array(
            'code'  => 0,
            'msg'   => '密码修改错误',
        ));
        
    }

    /**
     * 用户头像上传
     * 传入（post）
     *      id：用户id
     *      上传照片
     * 返回值：
     *      code：状态码
     *           0：上传错误
     *           1：上传成功
     *       msg：提示信息
     *           上传错误时，会提示相应的错误信息
     *       data：返回图片路径
     */
    public function avatarUpload(){
        if(IS_POST){
        $id = $_POST['id'];
        $imageUpload = new ImageController();
        $data = $imageUpload->upload('avatar');
        //上传成功，更新数据库
        if($data['code'] == 1){
            $user = M('User');
            $tmp = array('avatar_url' => $data['data'][0], 'id' => $id);
            //如果已存在文件，删除服务器上的文件
            if($avatar = $user->field('avatar_url')->where(array('id' => $id))->find()){
                unlink($avatar['avatar_url']);
            }
            $user->save($tmp);
            $data['data'] = $this->www_url . $data['data'][0];
        }
        $this->ajaxReturn($data);
        }else{
            $this->display();
        }
    }
    
     /**
     * 用户头像上传
     * 传入（post）
     *      id：用户id
     *      上传照片
     * 返回值：
     *      code：状态码
     *           0：上传错误
     *           1：上传成功
     *       msg：提示信息
     *           上传错误时，会提示相应的错误信息
     *       data：返回图片路径
     */
    public function bgUpload(){

        $id = $_POST['id'];
        $imageUpload = new ImageController();
        $data = $imageUpload->upload('background');
        //上传成功，更新数据库
        if($data['code'] == 1){
            $user = M('User');
            $tmp = array('cover_img' => $data['data'][0], 'id' => $id);
            //如果已存在文件，删除服务器上的文件
            if($avatar = $user->field('cover_img')->where(array('id' => $id))->find()){
                unlink($avatar['cover_img']);
            }
            $user->save($tmp);
            $data['data'] = $this->www_url . $data['data'][0];
        }
        $this->ajaxReturn($data);
    }
    
    /**
     * 微博发布
     * 传入参数
     *      id：模特id
     *      content：微博文字内容
     *      图片文件：命名规则两种方式：p1/p2/p3或者全部命名为p[]
     * 返回值--待定
     */
    public function postWeibo(){
        
        if(IS_POST){
            $id = $_POST['id'];
            $content = urldecode($_POST['content']);
            $imageUpload = new ImageController();
            $data = $imageUpload->upload('weibo', true);
            //上传成功，更新数据库
            if($data['code'] == 1){                
                //生成一条微博记录,插入文本内容
                $weibo_id = M('Weibo')->add(array('uid' => $id, 'content' => $content, 'add_time' => NOW_TIME));
                //微博图片信息存储
                $pic = M('Weibo_pic');
                foreach ($data['data'] as $key => $value){
                    $pic_type = $key==0 ? 1 : 0;    //如果是第一张图片设置为该条微博封面图
                    $pic_data = array('w_id' => $weibo_id, 'pic_url' => $value, 'pic_type' => $pic_type);
                    $pic->add($pic_data);
                    //修改返回url值
                    $data['data'][$key] = $this->www_url . $value;
                }
            }
            $this->ajaxReturn($data);
        } else {
            $this->display();
        }
    }
    
    /**
     * 删除自己的微博
     * @param type $wid
     */
    public function delMyWeibo($wid=0){
        if(M('Weibo')->delete($wid)){
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '删除成功',
            ));
        }else{
            $this->ajaxReturn(array(
                'code'  => 0,
                'msg'   => '删除失败'
            ));
        }
    }

    /**
     * 模特实名认证
     * @param int    $id      用户id      
     * @param string $realname 真实姓名
     * @param string $email    邮箱 
     * @param string $mobile   手机号码
     * @param string $cardid   身份证号
     * @return int 1：成功；0：失败；-1：邮箱格式错误；-2：手机号错误；-3：身份证号码错误
     */
    public function certification($id='', $realname='', $email='', $mobile='', $cardid=''){
        if(IS_POST){
            $imageUpload = new ImageController();
            $upload = $imageUpload->upload('card');
            $check = $this->checkFormat($email, $mobile);  //验证邮箱手机号码
            //邮箱、手机号码验证
            if($check < 0){
                $msg = $check==-1 ? '邮箱格式不正确' : '手机号码错误';
                $this->ajaxReturn(array(
                    'code'  => $check,
                    'msg'   => $msg,
                ));
            }
            //身份证号码验证
            if(!$this->checkCard($cardid)){
                $this->ajaxReturn(array(
                    'code'  => -3,
                    'msg'   => '身份证号码格式错误，男模特身份认证未开通',
                ));
            }
            //上传成功，保存信息
            if($upload['code'] == 1){
                $img = $upload['data'];
                $data = array(
                    'id'        => $id,
                    'realname'  => urldecode($_POST['realname']),
                    'email'     => $email,
                    'mobile'    => $mobile,
                    'cardid'    => $cardid,
                    'card_img'  => $img[0],
                    'status'    => 3,   //审核中状态
                );
                if(M('User')->save($data)){
                    M(User_model)->where(array('uid' => $id))->save(array('status' => 3));
                    $this->ajaxReturn(array(
                        'code'  => 1,
                        'msg'   => 'success',
                    ));
                }else{
                    $this->ajaxReturn(array(
                        'code' => 0,
                        'msg'  => '更新信息失败',
                    ));
                }
            }else{
                $this->ajaxReturn(array(
                    'code' => 0,
                    'msg'  => $upload['msg'],
                ));
            }
        }else{
            $this->display();
        }
    }
    
    /**
     * 检查邮箱以及手机号码格式
     * @param type $email   邮箱
     * @param type $mobile  手机号码
     * @return int -1,-2,1
     */
    public function checkFormat($email='', $mobile=''){
        preg_match('/^[\w\-\.]+@[\w\-\.]+(\.\w+)+$/', $email, $e_result);
        preg_match('/^1[3|4|5|8][0-9]\d{4,8}$/', $mobile, $m_result);
        if(!$e_result){
            return -1;
        }
        if(!$m_result){
            return -2;
        }
        return 1;
    }
    
    /**
     * 身份证号验证（格式、性别）
     * @param type $card 身份证号码
     * @return boolean
     */
    public function checkCard($card = ''){

        if(strlen($card) == 18){
            $map = array(1, 0, X, 9, 8, 7, 6, 5, 4, 3, 2);
            $sum = 0;
            for($i = 17; $i > 0; $i--){
                $s = pow(2, $i) % 11;
                $sum += $s * $card[17-$i];
            }

            if($map[$sum % 11]==strtoupper(substr($card, -1, 1)) && substr($card, -2, 1)%2==0){
                return TRUE;
            }
            return FALSE;
        }
        return FALSE;
    }
    
    /**
     * 模特卡上传
     * @param int $id 用户id
     */
    public function modelcardUpload($id=''){
        if(IS_POST){
            $imageUpload = new ImageController();
            $upload = $imageUpload->upload('modelcard');
            if($upload['code'] == 1){
                $img = $upload['data'];
                if(M('User_model')->where(array('uid' => $id))->save(array('model_card' => $img[0], 'model_card_updatetime' => NOW_TIME, 'show_model_card' => 0))){
                    $this->ajaxReturn(array(
                        'code'  => 1,
                        'msg'   => '上传成功',
                    ));
                }else{
                    $this->ajaxReturn(array(
                        'code' => -1,
                        'meg'  => '数据更新错误',
                    ));
                }
            } else {
                $this->ajaxReturn($upload);
            }
        }else{
            $this->display();
        }
    }
    
    /**
     * 获取麻豆卡
     * @param type $id 模特id
     */
    public function getModelCard($id){
        $model = M('User_model')->field('model_card')->
                where(array('uid' => $id, 'status' => 1, array('model_card' => array('neq', ''))))->find();
        if(!empty($model)){
            $this->ajaxReturn(array(
                'code'  => 1,
                'msg'   => '获取成功',
                'data'  => $this->www_url . $model['model_card'],
            ));
        }
        $this->ajaxReturn(array(
            'code'  => 0,
            'msg'   => '麻豆卡不存在',
        ));
    }
}